<?php 

class LsyiiEntityHelper
{
	
	/**
	 * 
	 * @param mixed $entity
	 * @return string
	 */
	static public function modelName($entity){
		$entityName = is_object($entity) ? LsClassInfo::GetEntityShortName($entity) : $entity;
		if($key = array_search($entityName, LsActiveRecord::$modelEntityMap)){
			return $key;
		}
	}
	
	/**
	 * 
	 * @param mixed $entity
	 * @return CActiveRecord
	 */
	static public function getModel($entity){
		if($modelName = self::modelName($entity)){
			return call_user_func(array($modelName, 'model'));
		}
	}
	
	/**
	 * 
	 * @return CActiveRecord
	 * @param Entity $entity
	 * @param boolean $checkInEntity
	 * @param boolean $find
	 */
	static public function getAr(Entity $entity, $checkInEntity=true, $find=false){
		if($checkInEntity && ($ar = $entity->getAr())){
			return $ar;
		}
		if(!($model = self::getModel($entity))){
			return;
		}
		
		$attrNames = $model->attributeNames();
		
		if($find){
			$pkName = $model->getMetaData()->tableSchema->primaryKey;
			if($pkName){
				$attrs = $entity->_getData((array) $pkName);
			}else{
				$attrs = $entity->_getData($attrNames);
			}
			$ar = $model->findByAttributes($attrs);
		}else{
			$modelClass = get_class($model);
			$ar = new $modelClass;
			$attrs = $entity->_getData($attrNames);
			$ar->setAttributes($attrs, false);
			$ar->setIsNewRecord(false);
		}
		
		if($ar){
			$entity->setAr($ar);
			return $ar;
		}
	}
	
	static public function getRelated(Entity $entity, $relationName, $refresh=false, $params=array()){
		if(!($ar = $entity->getAr())){
			return;
		}
		$related = $ar->getRelated($relationName, $refresh, $params);
		if(is_object($related)){
			$relatedEntity = $related->getEntity();
			return $relatedEntity ? $relatedEntity : $related;
		}elseif(is_array($related)){
			$result = array();
			foreach($related as $index => $relatedAr){
				$relatedEntity = $relatedAr->getEntity();
				$result[$index] = $relatedEntity ? $relatedEntity : $relatedAr;
			}
			return $result;
		}
		return $related;
	}
	
}

?>